#!/bin/bash

echo "k8s deploy beginning"

name=${JOB_NAME}
namespace=${BRANCH}
image=$(cat ${WORKSPACE}/IMAGE)
branch=${BRANCH}
urlpath=${urlpath}

echo "deploying ... name:${name},namespace:${namespace},image:${image},branch:${branch}"

# map 通过index获取
prevision=$(kubectl get deployment.apps/${name} -n ${branch} -o go-template='{{index .metadata.annotations "deployment.kubernetes.io/revision"}}' 2>/dev/null || echo 0)
echo "deployment prevision:${prevision}"

rm -f web.yaml
# BASH_SOURCE[0]:当前执行的bash脚本全路径，dirname:获取当先执行脚本所在目录（去除文件名部分）
cp $(dirname "${BASH_SOURCE[0]}")/template/web.yaml .

sed -i "s,{{name}},${name},g" web.yaml
sed -i "s,{{namespace}},${namespace},g" web.yaml
sed -i "s,{{image}},${image},g" web.yaml
sed -i "s,{{branch}},${branch},g" web.yaml
sed -i "s,{{urlpath}},${urlpath},g" web.yaml

kubectl apply -f web.yaml || exit 1

vision=$(kubectl get deployment.apps/${name} -n ${branch} -o go-template='{{index .metadata.annotations "deployment.kubernetes.io/revision"}}' 2>/dev/null || echo 0)
echo "deployment current vision:${vision}"

echo "k8s deploy finished"

cat web.yaml
echo ""

# 健康检查
success=0
count=60
IFS=","
#sleep=5
while [ ${count} -gt 0 ]; do
  if [ ${vision} == $((${prevision} + 1)) ]; then
    replicas=$(kubectl get deployment.apps/${name} -n ${branch} -o go-template='{{.status.replicas}},{{.status.updatedReplicas}},{{.status.readyReplicas}},{{.status.availableReplicas}}')
    echo "replicas: ${replicas}"
    arr=(${replicas})
    if [ "${arr[0]}" == "${arr[1]}" -a "${arr[1]}" == "${arr[2]}" -a "${arr[2]}" == "${arr[3]}" ]; then
      echo "health check success!"
      success=1
      break
    fi
    else
      echo "waiting deployment ..."
  fi
  ((count--))
  sleep 2
done
# -ne 不等于
if [ ${success} -ne 1 ]; then
  echo "health check failed!"
  exit 1
fi


